import { getOffsetSum, Ne, Qi, scrollDom } from "./utils"

//全局变量
const g = window.SWOFD
// 文档模型
// 默认旋转
const rotate = 0
let dpi = 96
let page

export default class InitDoc {
    constructor (contentEl) {
        this.index = 0
        this.contentEl = contentEl
        this.contentEl.style.width = '100%'
        this.contentEl.style.height = '100%'
        this.contentEl.style.overflow = 'auto'
        // 为主文档区域绑定滚动事件
    
        this.contentEl.addEventListener('scroll', () => {
           
            console.log("执行渲染")
           scrollDom(this.paint())
           
        })
    }
    // 清空已渲染的dom 重设属性
    resetDom () {
        this.contentEl.innerHTML = ''
    }

    // 打开文档获取文档对象
    async openDoc (file) {
        this.doc = await g.open(file)
        if (this.doc) {
            this.count = this.doc.pageCount
        }
        this.renderDom()
    }
    // 渲染dom
    async renderDom () {
        this.resetDom()
        const fristPage = await this.doc.pageAt(0)
        let width, height
        if (fristPage) {
            // 页面原始宽高
            const [ow, oh] = fristPage.size()
            // 页面旋转宽高
            const [w, h] = await g.Tool.ratote(rotate, [ow, oh])
            // 根据主渲染区域设置适合宽高的dpi
            width = await g.Tool.mm2px(w, dpi)
            height = await g.Tool.mm2px(h, dpi)
        }
        for (let i = 0; i < this.count; i++) {
            const paperDiv = Ne('div')
            paperDiv.setAttribute('class', 'paper-div')
            paperDiv.style.textAlign = 'center'
            const paper = Ne('div')
            paper.setAttribute('id', 'paper' + i)
            paper.setAttribute('class', 'paper')
            paper.setAttribute('data-index', i.toString())
            paper.style.width = width + 'px'
            paper.style.height = height + 'px'
            paper.style.display = 'inline-block'
            paperDiv.appendChild(paper)
            this.contentEl.appendChild(paperDiv)
        }
    }
    inView (dom) {
        // 判断在可视范围内
        // dom, this.contentEl
     /*    let returns=getOffsetSum(dom) */
        if(window.innerHeight+document.documentElement.scrollTop>dom.offsetTop){
            return true
        }     
    }
    async paint(){ 
        if (!this.doc) {
            console.log('OFD文档未打开');
            return;
        }
        for (let i = 0; i < this.count; i++) {
            let pageInView = this.inView(Qi('paper' + i))
            if (pageInView) {
                page = await this.doc.pageAt(i);
                if (page) {
                    await page.paint(Qi('paper' + i), { dpi: 96, selectText: false, rotate: 0 });  
                }
            }
        }
        console.log("执行渲染")
    }
    zoon(){
        this.renderDom();
        
    }
  
}
